home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1993…ch: Other People's Memory / ADC Developer CD (1993-03) (''Other People's Memory'')_iso / Dev.CD Mar 93.iso / Development Platforms / LISP Related / LISP Goodies / btree / btree.lisp < prev    next >
Encoding:
Text File  |  1992-09-02  |  51.2 KB  |  1,510 lines  |  [TEXT/CCL2]

  1. (in-package :btree)
  2.  
  3. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  4. ;; btree.lisp
  5. ;;
  6. ;; Copyright © 1992 University of Toronto, Department of Computer Science
  7. ;; All Rights Reserved
  8. ;;
  9. ; author: Mark A. Tapia markt@dgp.toronto.edu or markt@dgp.utoronto.ca
  10. ;; 
  11. ;; Package for manipulating balanced avl trees.
  12. ;;
  13. ;; Acknowledgements:
  14. ;;
  15. ;; Revision history:
  16. ;;
  17. ;; Work to do:
  18. ;;   Support tree-merging and concatenation (an entire tree is to be inserted
  19. ;;   to the right of an existing tree).
  20. ;;  
  21. ;; Within avl-tree, order-function is a function of two arguments (u v)
  22. ;; reflecting a total ordering on the keys.
  23. ;; The value returned is one of {*equal*, *before*, *after*}
  24. ;;   when (u = v), (order-function u v) = *equal*
  25. ;;        (u < v), (order-function u v) = *before*
  26. ;;        (u > v), (order-function u v) = *after*
  27. ;;
  28. ;;  The algorithms are based on the balanced tree algorithms in Knuth
  29. ;;  The Art of Computer Programming, Searching and Sorting Volume III
  30. ;;  sections 6.2.2 - 6.2.4 with modifications.
  31. ;; 
  32. ;;  The balanced trees are red-black trees augmented with points to
  33. ;;  allow fast reporting and updating. The representation is described in
  34. ;;  Cheng SW and Janardon R, "Efficient maintenance of the union intervals 
  35. ;;  on a line, with applications", Proceedings of the First Annual ACM-SIAM 
  36. ;;  Symposium on Discrete Algorithms, SIAM pp74-83.
  37. ;;
  38. ;;  The additional fields are marked with an asterisk (*)
  39. ;;
  40. ;;  Given a btree record for a non-null node v, the following fields are defined
  41. ;;  *   min     - either a pointer to the leftmost leaf of the subtree
  42. ;;                or nil if v is the leftmost node of the tree rooted at v
  43. ;;  *   max     - either a pointer to the rightmost leaf of the subtree
  44. ;;                or nil if v is the rightmost node of the tree rooted at v
  45. ;;      key     - the key associated with v
  46. ;;      val     - the value associated with the key key of v
  47. ;;      left    - a pointer to the left children of v
  48. ;;      right   - a pointer to the right children of v
  49. ;;      balance - the balance factor of the rooted subtree v
  50. ;;                *balanced*     - the right and left branches are equal in height
  51. ;;                *right-taller* - the right branch is one level taller than the left
  52. ;;                *left-taller*  - the left branch is one level taller than the right
  53. ;;
  54.  
  55. (eval-when (eval compile)
  56.   (require 'btree-decl)
  57.   (require 'macros))
  58.  
  59. (provide 'btree)
  60.  
  61. (export '(add-node
  62.           delete-node
  63.           find-path
  64.           find-key
  65.           *copy-btree
  66.           direct-find-key
  67.           print-path
  68.           print-tree
  69.           from-btreek
  70.           root-path
  71.           to-btreek
  72.           is-leaf
  73.           max-val
  74.           min-val
  75.           *to-btree
  76.           get-next-node
  77.           operate-on-tree
  78.           find-root) :btree)
  79.  
  80.  
  81. (setf *print-circle* t)
  82.  
  83. (defparameter *debug* nil)
  84.  
  85. (defun is-debug ()
  86.   *debug*)
  87.  
  88. ;;; macros
  89.  
  90. (defmacro found-node (new-node path)
  91.   `(push (list *equal* ,new-node) ,path))
  92.  
  93. (defmacro root-path (root)
  94.   "A path consisting of the root of the tree"
  95.   `(when ,root
  96.      (list (list *equal* ,root))))
  97.  
  98. (defmacro select (exp &body body)
  99.   (let ((var (gensym)) code condition)
  100.     (dolist (frag body)
  101.       (setf condition (nth 0 frag))
  102.       (push
  103.        (cons
  104.         (if (member condition '(t otherwise))
  105.           t
  106.           (list 'equal var condition))
  107.         (rest frag))
  108.        code))
  109.     (setf code (nreverse code))
  110.     (push 'cond code)
  111.     (setf code (list code))
  112.     (push `((,var ,exp)) code)
  113.     (push 'let code)
  114.     `,code))
  115.  
  116. (defmacro add-turn (new-node node temp path dir)
  117.   `(progn
  118.      (if (= ,dir *right*)
  119.        (setf (btree-right ,node) ,new-node)
  120.        (setf (btree-left ,node) ,new-node))
  121.      (setf (btrail-dir ,temp) ,dir)
  122.      (found-node ,new-node ,path)))
  123.  
  124. #|
  125. ;; example
  126. (defvar fruit 'apple)
  127. (select fruit
  128.         ('apple 'doctor)
  129.         ('peach 'lover)
  130.         (otherwise nil))
  131. ;; prints doctor
  132. |#
  133.  
  134. ;; Macro which performs operations on a btree, starting at the root.
  135. ;;
  136. ;; When the root is empty:
  137. ;;    1. Executes the null-action
  138. ;; Otherwise threads through the tree from top to bottom and left to right,
  139. ;; applying the following actions:
  140. ;;    1. Applies the node-action to the tree 
  141. ;;    2. Binds the node to the left branch and binds the left positional parameter to the node. 
  142. ;;       When the left branch is not empty, evaluates the expression
  143. ;;       corresponding to the branch action.
  144. ;;    2. Binds the node to the right branch and binds the left positional parameter to the node. 
  145. ;;       When the left branch is not empty, evaluates the expression
  146. ;;       corresponding to the branch action.
  147. ;;    4. Evaluates and returns the return expression.
  148. ;;    
  149. (defmacro operate-on-tree ((node tree &optional (left (gensym)) (right (gensym))) &key
  150.                            (return nil)
  151.                            null-action
  152.                            node-action 
  153.                            branch-action)
  154.   `(let (,node ,left ,right)
  155.      (declare (ignorable ,left ,right))
  156.      (if (null ,tree)
  157.        ,null-action
  158.        (progn
  159.          ,node-action
  160.          (when (setq ,node (btree-left ,tree)
  161.                      ,left ,node)
  162.            ,branch-action)
  163.          (when (setq ,node (btree-right ,tree)
  164.                      ,right ,node)
  165.            ,branch-action)
  166.          ,return))))
  167.  
  168. #| 
  169. ;; Basic example: visits every node and does nothing, returning the tree
  170. (defun walk-tree (tree)
  171.   (operate-on-tree (node tree)
  172.                    :return tree))
  173.  
  174. ;; Prints all nodes in a path starting from the root, 
  175. ;; composed of alternating left and right turns,
  176. (defun print-turn (tree &optional (dir *left*))
  177.   (operate-on-tree (node tree left right)
  178.                    :node-action (print (btree-key tree))
  179.                    :branch-action (if (equal dir *left*)
  180.                                     (when (eq node left) (print-turn node *right*))
  181.                                     (when (eq node right) (print-turn node *left*)))))
  182.  
  183. ;; Returns a sorted list of the keys of a btree in descending order
  184. (defun print-key (tree &optional values)
  185.   (let (print-node)
  186.     (operate-on-tree (node tree left right) 
  187.                      :node-action (setq print-node t)
  188.                      :branch-action (if (eq node left)
  189.                                       (setq values (print-key node values))
  190.                                       (progn (push (btree-key tree) values)
  191.                                              (setq values (print-key node values))
  192.                                              (setq print-node nil)))
  193.                      :return (progn 
  194.                                (when 
  195.                                  print-node (push (btree-key tree) values))
  196.                                values))))
  197. |#
  198.  
  199. ;; basic copy function
  200.  
  201. (defun *copy-btree (u &optional (descend 0))
  202.   "Create a copy of a btree using the integer descend to control how
  203. to copy the values.
  204. Copy the keys using copy-tree.
  205. Copy the values in one of two ways:
  206.    If descend > 0, decrement descend and
  207.      copy the btrees corresponding to the node values.
  208.    Otherwise use copy-tree to copy the values"
  209.   (let* ((val (if (> descend 0)
  210.                 (*copy-btree (btree-val u) (1- descend))
  211.                 (copy-tree (btree-val u))))
  212.          new-node 
  213.          min
  214.          max)
  215.     (operate-on-tree (node u left right)
  216.                      :node-action (setq new-node (make-btree :key (copy-tree (btree-key u))
  217.                                                              :val val
  218.                                                              :balance (btree-balance u)))
  219.                      :branch-action (*copy-btree node descend)
  220.                      :return (progn
  221.                                (setq min (or (btree-min left) left)
  222.                                      max (or (btree-max right) right))
  223.                                (setf (btree-min new-node) min
  224.                                      (btree-max new-node) max
  225.                                      (btree-right new-node) right
  226.                                      (btree-left new-node) left)
  227.                                new-node))))
  228.  
  229. ;; basic comparison functions
  230. (defun compare (m n)
  231.   ;; for integers m and n, behaves like a fortran computed if
  232.   (cond ((= m n) *equal*)
  233.         ((< m n) *before*)
  234.         (t *after*)))
  235.  
  236. (defun is-less (a b the-pred)
  237.   (= (funcall the-pred a b) *before*))
  238.  
  239. ;; basic tree functions
  240. (defun check-tree (tree min max)
  241.   "determines whether the tree is height balanced and all nodes in the tree
  242. are between min and max"
  243.   (and (all-height-balanced tree)
  244.        (check-tree1 tree min max)))
  245.  
  246. (defun check-tree1 (tree min max)
  247.   "determines whether the nodes in the tree range between the min and max
  248. values of the parent"
  249.   (let (node)
  250.     (if (null tree)
  251.       t
  252.       (and
  253.        (if (or (> (btree-key tree) max)
  254.                (< (btree-key tree) min))
  255.          (progn
  256.            (print-db max min (btree-key tree)
  257.                      (> (btree-key tree) max)
  258.                      (< (btree-key tree) min))
  259.            (print-tree tree)
  260.            nil)
  261.          t)
  262.        (progn
  263.          (setq node (btree-left tree))
  264.          (and (or (null node)
  265.                   (<= (min-val node) (btree-key tree)))
  266.               (check-tree1 node (min-val node) (max-val node))))
  267.        (progn (setq node (btree-right tree))
  268.               (and (or (null node)
  269.                        (>= (max-val node) (btree-key tree))) 
  270.                    (check-tree1 node (min-val node) (max-val node))))))))
  271.  
  272. ;; btree height functions
  273.  
  274. (defun metric-btree (btree)
  275.   "Print a count of the number of nodes in a tree, the maximum height and 
  276. the deviation from the ideal"
  277.   (let ((nodes (count-nodes btree))
  278.         (height (height-btree btree)))
  279.     (format t "~&nodes=~d height=~d ideal/actual = ~d%~%"
  280.             nodes height (round (* 100 (log nodes 2))  height)
  281.             )))
  282.  
  283. (defun height-btree (btree &optional (n 0))
  284.   (if (null btree) n
  285.       (max (height-btree (btree-left btree) (1+ n))
  286.            (height-btree (btree-right btree) (1+ n)))))
  287.  
  288. (defun count-nodes (btree)
  289.   (if (null btree) 0
  290.       (+ (1+ (count-nodes (btree-left btree)))
  291.          (count-nodes (btree-right btree)))))
  292.  
  293. ;; link routines from Knuth 
  294. (defun link (dir node)
  295.   ;;  (link *right* node) = (btree-right node)
  296.   ;;  (link *left* node)  = (btree-left node)
  297.   (if (equal dir *right*)
  298.     (btree-right node)
  299.     (btree-left node)))
  300.  
  301. (defun set-link (dir node value)
  302.   ;;  (set-link *right* node value) = (setf (btree-right node) value)
  303.   ;;  (set-link *left* node value)  = (setf (btree-left node) value)
  304.   (when node
  305.     (if (equal dir *right*)
  306.       (setf (btree-right node) value)
  307.       (setf (btree-left node) value))))
  308.  
  309. ;;; Printing
  310. ;;       trees
  311. (defun balance-string (node)
  312.   (select (btree-balance node)
  313.     (*right-taller* "R")
  314.     (*left-taller* "L")
  315.     (*balanced* " ")
  316.     (otherwise "?")))
  317.  
  318. (defun direction-string (dir)
  319.   (select dir
  320.     (*right* "R")
  321.     (*left* "L")
  322.     (*equal* " ")
  323.     (otherwise ".")))
  324.  
  325. (defun tree-direction-string (dir)
  326.   (select dir
  327.     (*right* "L:")
  328.     (*left* "R:")
  329.     (otherwise "=:")))
  330.  
  331. (defun print-node (u level dir &key title)
  332.   (format t "~&~@?~a ~s ~a [~d ~d] ~a~%"
  333.           (format nil "~~~dt"  level)
  334.           (balance-string u)
  335.           (btree-key u)
  336.           (direction-string dir)
  337.           (btree-key (btree-min u))
  338.           (btree-key (btree-max u))
  339.           (if title
  340.             title
  341.             " ")))
  342.  
  343. (defun print-tree (u &key title)
  344.   (when title
  345.     (format t "~&~a~%" title))
  346.   (print-tree1 u 1 *equal*))
  347.  
  348. (defun print-tree1 (u level dir)
  349.   (when u
  350.     (print-node u level dir)
  351.     (print-tree1 (btree-left u) (1+ level) *left*)
  352.     (print-tree1 (btree-right u) (1+ level) *right*)))
  353.  
  354. (defun print-root (path)
  355.   (print-tree (find-root path)))
  356.  
  357. ;;      Paths
  358. (defun print-path (path &key title)
  359.   (let (key direction)
  360.     (format t "~&~a Path length ~d ~%"
  361.             (if title title " ")
  362.             (length path))
  363.     (dolist (u path)
  364.       (setf direction (btrail-dir u)
  365.             key (btrail-node u))
  366.       (if direction
  367.         (format t "~&~s ~a [~s ~s] ~d~%"
  368.                 (btree-key key)
  369.                 (direction-string direction)
  370.                 (btree-key (btree-min key))
  371.                 (btree-key (btree-max key))
  372.                 (balance-string key))
  373.         (format t "~&~s~%" key)))))
  374.  
  375. ;; basic path routines
  376. (defun is-root (path)
  377.   (or (null path) (null (rest path))))
  378.  
  379. ;; converting to/from trees and lists
  380. ;;  (to-btree (from-btree tree) order-function) = tree
  381. ;;  (from-btree (to-btree list order-function)) = list 
  382.  
  383. (defun to-btreek (key-list order-function &key debug)
  384.   "Converts the list of keys in key-list to a btree with 
  385. key =  value.  Uses the order-function
  386. that returns *before* *equal* *after* and optionally prints the 
  387. tree as it is being assembled"
  388.   (let (root path a-key title)
  389.     (when key-list
  390.       (setf root (make-btree 
  391.                   :key (setq a-key (pop key-list))
  392.                   :val a-key)
  393.             path (root-path root))
  394.       (loop for a-key in key-list
  395.             do (setf path (add-node a-key a-key (root-path root) order-function))
  396.             (setq root (find-root path))
  397.             (when debug
  398.               (setf title (format nil "**add ~s" a-key)) 
  399.               (print-path path :title title) 
  400.               (print-tree root :title title)))
  401.       root)))
  402.  
  403. (defun to-btree (key-list order-function &key debug)
  404.   "Converts the list of (key value) in key-list to a btree.
  405. Uses the order-function that returns *before* *equal* *after* 
  406. and optionally prints the 
  407. tree as it is being assembled"
  408.   (let (root path key-part title)
  409.     (when key-list
  410.       (setf key-part (pop key-list)
  411.             root (make-btree 
  412.                   :key (first key-part)
  413.                   :val (second key-part)
  414.                   :balance *balanced*)
  415.             path (root-path root))
  416.       (dolist (key-part key-list)
  417.         (setq path
  418.               (add-node (first key-part)
  419.                         (second key-part)
  420.                         path
  421.                         order-function))
  422.         (when debug
  423.           (setf title (format nil "**add ~s" (first key-part))) 
  424.           (print-path path :title title) 
  425.           (print-tree root :title title)))
  426.       root)))
  427.  
  428. (defun from-btree (tree)
  429.   "Convert a btree to a list of the form ((key val) ... (keyn valn)) sorted by key"
  430.   (nreverse (from-btree1 tree nil)))
  431.  
  432. (defun from-btree1 (tree nodes)
  433.   ;; covert to a list sorted by key in descending order
  434.   (let (print-node)
  435.     (operate-on-tree (node tree left right)
  436.                      :node-action (setq print-node t)
  437.                      :branch-action (if (eq node left)
  438.                                       (setq nodes (from-btree1 node nodes))
  439.                                       (progn
  440.                                         (push  (list (btree-key tree)
  441.                                                      (btree-val tree))
  442.                                                nodes)
  443.                                         (setq print-node nil)
  444.                                         (setq nodes (from-btree1 node nodes))))
  445.                      :return (progn 
  446.                                (when print-node
  447.                                  (push  (list (btree-key tree)
  448.                                               (btree-val tree))
  449.                                         nodes))
  450.                                nodes))))
  451.  
  452. ;; --> basic node routines
  453. (defun check-leaf (node)
  454.   "For a leaf node, fills in the min and max and balance fields."
  455.   (when (and node (is-leaf node))
  456.     (setf (btree-balance node) *balanced*
  457.           (btree-max node) nil
  458.           (btree-min node) nil)))
  459.  
  460. (defun is-leaf (node)
  461.   "Returns t iff the node is a leaf node"
  462.   (or (null node)
  463.       (and (null (btree-left node))
  464.            (null (btree-right node)))))
  465.  
  466. (defun replace-node (source replacement)
  467.   "When source and replacement are lists, interchanges the two lists"
  468.   (when (and source (listp source) (listp replacement))
  469.     (setf (first source) (first replacement)
  470.           (rest source) (rest replacement))))
  471.  
  472. (defun interchange-nodes (node1 node2)
  473.   "Interchanges node1 and node2"
  474.   (let ((temp-node (copy-list node1)))
  475.     (replace-node node1 node2)
  476.     (replace-node node1 temp-node)))
  477.  
  478. (defun swap-key (node1 node2 &key balance)
  479.   "Swaps the keys associated with btrede nodes node1 and node2 and optionally swaps the balance"
  480.   (unless (and node1 node2)
  481.     (break "bad-swap-nodes"))
  482.   (rotatef (btree-key node1) (btree-key node2))
  483.   (rotatef (btree-val node1) (btree-val node2))
  484.   (when balance
  485.     (rotatef (btree-balance node1) (btree-balance node2))))
  486.  
  487. (defun copy-info (source destination &key left right max min balance)
  488.   "Copies selected fields from the source to the destination node.
  489. By default replaces the key and values fields in the destination by the source.
  490. When the keyword parameter values are non nil, replaces these fields as well"
  491.   (unless (and source destination)
  492.     (break "bad-copy"))
  493.   (setf (btree-key destination) (btree-key source)
  494.         (btree-val destination) (btree-val source))
  495.   (when left
  496.     (setf (btree-left destination) (btree-left source)))
  497.   (when right
  498.     (setf (btree-right destination) (btree-right source)))
  499.   (when max
  500.     (setf (btree-max destination) (btree-max source)))
  501.   (when min
  502.     (setf (btree-min destination) (btree-min source)))
  503.   (when balance
  504.     (setf (btree-balance destination) (btree-balance source)))
  505.   destination)
  506.  
  507. ;; --> min/max routines
  508.  
  509. (defun get-max (node)
  510.   "Return the rightmost node in the tree rooted at node"
  511.   (or (btree-max node)
  512.       node))
  513.  
  514. (defun get-min (node)
  515.   "Return the leftmost node in the tree rooted at node"
  516.   (or (btree-min node)
  517.       node))
  518.  
  519. (defun max-val (node)
  520.   "Return the key associated with the rightmost node in the tree rooted at node"
  521.   (let ((max-node (get-max node)))
  522.     (btree-key 
  523.      max-node)))
  524.  
  525. (defun min-val (node)
  526.   "Return the key associated with the leftmost node in the tree rooted at node"
  527.   (let ((min-node (get-min node)))
  528.     (btree-key 
  529.      min-node)))
  530.  
  531. (defun put-min-max (min-max default &optional other)
  532.   "Returns the first non-null value in min-max default other" 
  533.   (or min-max
  534.       default
  535.       other))
  536.  
  537. (defun set-min-max (node &optional (descend 0))
  538.   (when node
  539.     (when (> descend 0)
  540.       (set-min-max (btree-val node) (1- descend)))
  541.     (if (is-leaf node)
  542.       (values node node)
  543.       (let ((min (set-min-max (btree-left node) descend)))
  544.         (multiple-value-bind (minr max)
  545.                              (set-min-max (btree-right node) descend)
  546.           (declare (ignore minr))
  547.           (setf (btree-min node) min
  548.                 (btree-max node) max)
  549.           (values min max))))))
  550.  
  551. (defun supply-min/max (parent child)
  552.   "If child is the left/right node of the parent, returns the node;
  553. otherwise returns the parent"
  554.   (if child
  555.     child
  556.     parent))
  557.  
  558. (defun fix-max-min (node)
  559.   "Ensures that the node has the proper min and max links and that
  560. the left and right children are fixed if they are leaves."
  561.   (let (left right)
  562.     (when node
  563.       (setq left (btree-left node)
  564.             right (btree-right node))
  565.       (check-leaf left)
  566.       (check-leaf right)
  567.       (setf (btree-min node) (put-min-max (get-min left) left)
  568.             (btree-max node) (put-min-max (get-max right) right))
  569.       (when (is-debug) 
  570.         (print-db (btree-key node) (min-val node) (max-val node))))))
  571.  
  572. (defun q-adjust-max (path)
  573.   "Adjusts a path of the form (dir node) ... (dir node)
  574. setting the max  links appropriately  for each node for all right turns"
  575.   (let (new-max)
  576.     (when path
  577.       (setq new-max (get-max (btrail-node (first path)))))
  578.     (loop for temp in (rest path)
  579.           with dir and node
  580.           do (setq dir (btrail-dir temp) 
  581.                    node (btrail-node temp))
  582.           until (equal dir *left*)
  583.           do (setf (btree-max node)
  584.                    (unless (eq new-max node)
  585.                      new-max)))))
  586.  
  587. (defun q-adjust-max-min (path)
  588.   "Adjusts a path of the form (dir node) ... (dir node)
  589. setting the max (and min) links appropriately for each node for all right (and left) turns"
  590.   (q-adjust-max path)
  591.   (q-adjust-min path))
  592.  
  593. (defun q-adjust-min (path)
  594.   "Adjusts a path of the form (dir node) ... (dir node)
  595. setting the min links appropriately for all left turns"
  596.   (let (new-min)
  597.     (when path
  598.       (setq new-min (get-min (btrail-node (first path)))))
  599.     (loop for temp in (rest path)
  600.           with dir and node
  601.           do (setq dir (btrail-dir temp) 
  602.                    node (btrail-node temp))
  603.           until (equal dir *right*)
  604.           do (setf (btree-min node)
  605.                    (unless (eq new-min node)
  606.                      new-min)))))
  607.  
  608. (defun adjust-max (new-max path)
  609.   "Adjusts a path of the form (dir node) ... (dir node)
  610. setting the max links appropriately for each node for all right turns"
  611.   (loop for temp in path 
  612.         with dir and node
  613.         do (setq dir (btrail-dir temp) 
  614.                  node (btrail-node temp))
  615.         until (equal dir *left*)
  616.         do (setf (btree-max node)
  617.                  (unless (eq new-max node)
  618.                    new-max))))
  619.  
  620. (defun adjust-min (new-min path)
  621.   (let (node)
  622.     (dolist (temp path)
  623.       (setf node (btrail-node temp))
  624.       (if (eq node new-min)
  625.         (setf (btree-min node) nil)
  626.         (select (btrail-dir temp)
  627.           (*equal* (setf (btree-min node) nil))
  628.           (*right* (return t))
  629.           (*left*
  630.            (setf (btree-min node)
  631.                  (if (eq new-min node)
  632.                    nil
  633.                    new-min))))))))
  634.  
  635. ;; --> turn routines
  636.  
  637. (defun extreme-turn (path dir)
  638.   "continue turning in the direction dir from the last node in path 
  639. until no more dir turns are possible"
  640.   (let (temp node old-path)
  641.     (loop
  642.       (setf temp (first path)
  643.             node (btrail-node temp))
  644.       (when (or (is-leaf node) (eq path old-path))
  645.         (return path))
  646.       (setf old-path path
  647.             path (turn-immediate path dir)))))
  648.  
  649. (defun extreme-left (path)
  650.   "continue turning left from the last node in path 
  651. until no more left turns are possible"
  652.   (extreme-turn path *left*))
  653.  
  654. (defun extreme-right (path)
  655.   "continue turning right from the last node in path 
  656. until no more right turns are possible"
  657.   (extreme-turn path *right*))
  658.  
  659. (defun turn (path dir)
  660.   "Turn in the direction dir from the last node in the path"
  661.   (let (temp
  662.         old-dir
  663.         new-node
  664.         node 
  665.         (old-path path))
  666.     (loop
  667.       (unless path
  668.         (return old-path))
  669.       (setf temp (first path)
  670.             old-dir (btrail-dir temp)
  671.             node (btrail-node temp)
  672.             new-node (select old-dir
  673.                        (*equal* (turn1 node dir)) ; haven't already turned left or right
  674.                        (*before* 
  675.                         (when (= dir *right*) ; haven't already turned right
  676.                           (turn1 node dir)))))
  677.       (when new-node
  678.         (setf (btrail-dir temp) dir)
  679.         (found-node new-node path)
  680.         (return path))
  681.       (pop path))))
  682.  
  683. (defun turn-immediate (path dir)
  684.   "Make a dir (left/right) turn from the last node in path"
  685.   (let* ((temp (first path))
  686.          (node (btrail-node temp))
  687.          new-node)
  688.     ; when the node is not a leaf and it is possible to turn in the dir direction
  689.     (unless (or (is-leaf node)
  690.                 (null (setf new-node (turn1 node dir))))
  691.       (setf (btrail-dir temp) dir)
  692.       (found-node new-node path)
  693.       path)))
  694.  
  695. (defun turn1 (node dir)
  696.   (when node
  697.     (select dir
  698.       (*left* (btree-left node))
  699.       (*right*  (btree-right node))
  700.       (otherwise node))))
  701.  
  702. (defun retract-path (key path order-function)
  703.   "Backup through the path branch by branch
  704. until either the path is empty or the node with the key lies in the rooted subtree"
  705.   (let (temp new-key dir new-node)
  706.     (when (and path (null (btrail-dir (first path))))
  707.       (pop path))
  708.     (loop
  709.       (unless path
  710.         (return path))
  711.       (setf temp (first path)
  712.             dir (btrail-dir temp)
  713.             new-node (btrail-node temp)
  714.             new-key (btree-key new-node))
  715.       (select (funcall order-function key new-key)
  716.         (*equal*
  717.          (return path))
  718.         (*after*
  719.          (unless (= (funcall order-function key (max-val new-node)) *after*)
  720.            (unless (= dir *right*)
  721.              (return (setf path (turn path *right*))))))
  722.         (*before*
  723.          (if (= dir *equal*)
  724.            (return  
  725.             (if (= (funcall order-function key (min-val new-node)) *before*)
  726.               (setf path (turn path *left*)))))))
  727.       (pop path))))
  728.  
  729. (defun retract-to-right (path)
  730.   "Retract the path to the node associated with nearest rooted subtree
  731. whose orig-dir (left/right) branch has not yet been explored"
  732.   (let (temp
  733.         node
  734.         dir
  735.         orig-dir)
  736.     (loop
  737.       do (pop path)
  738.       while path
  739.       do (setf temp (first path)
  740.                node (btrail-node temp)
  741.                dir (btrail-dir temp))
  742.       unless orig-dir do (setf orig-dir dir)
  743.       while (and (not (is-leaf node))
  744.                  (not (= dir orig-dir))
  745.                  (btree-right node)))
  746.     path))
  747.  
  748. ;; --> find routines
  749.  
  750.  
  751.  
  752. (defun find-key (key root order-function)
  753.   "Given the key, the root of a btree and the order-function for key comparison:
  754. return the value of the node associated with the key
  755. or nil when it is not found"
  756.   (let ((node root)
  757.         (dir *equal*))
  758.     (loop
  759.       (unless node
  760.         (return nil))
  761.       (select (funcall order-function key (btree-key node))
  762.         (*equal*
  763.          (return (btree-val node)))
  764.         (*before*
  765.          (if (or (is-leaf node)
  766.                  (null (setf node (btree-left node)))
  767.                  (and (not (= dir *left*))
  768.                       (= (funcall order-function key
  769.                                   (min-val node))
  770.                          *before*)))
  771.            (return nil)
  772.            (setf dir *left*)))
  773.         (*after*
  774.          (if (or (is-leaf node)
  775.                  (null (setf node (btree-right node)))
  776.                  (and (not (= dir *right*))
  777.                       (= (funcall order-function key
  778.                                   (max-val node))
  779.                          *after*)))
  780.            (return nil)
  781.            (setf dir *right*)))))))
  782.  
  783. (defun fast-find (root keys order-function)
  784.   "Given a set of keys, a binary tree root and an order-function.
  785. Sort the keys using the order function. Return t if all
  786. of the keys are in the tree, otherwise return nil."
  787.   (let ((path (root-path root)))
  788.     (flet ((sort-pred (u v)
  789.              (= (funcall order-function u v) *before*)))
  790.       (setf keys (sort keys #'sort-pred))
  791.       (loop for a-key in keys
  792.             do (setf path (find-path a-key path :order-function order-function))
  793.             when (or (null path)
  794.                      (null (btrail-dir (first path)))) do (return nil)
  795.             finally (return t)))))
  796.  
  797. (defun delete-extreme-left (path parent-node first-right)
  798.   "Delete the parent node. 
  799. First-right = (btree-right parent-node).
  800. and path is a right turn from the path to the parent node.
  801. Copy the keys and val of extreme left node of first-right
  802. into the parent node and remove the extreme-left node, modifying the tree" 
  803.   (declare (ignore first-right))
  804.   (loop with old-path = path and node and prev-node and right-node
  805.         do (setq path (turn-immediate path *left*))
  806.         until (null path)
  807.         do (setq old-path path)
  808.         finally (progn
  809.                   (setq path old-path)
  810.                   (setq node (btrail-node (first path))
  811.                         prev-node (btrail-node (second path)))
  812.                   (copy-info node parent-node)
  813.                   (setq right-node (btree-right node))
  814.                   (if (is-leaf node)
  815.                     (progn 
  816.                       (setf (btree-left prev-node) nil
  817.                             (btree-min prev-node) nil)
  818.                       (pop path))
  819.                     (progn
  820.                       (setq path (turn-immediate path *right*))
  821.                       (copy-info right-node node :left t :right t
  822.                                  :max t :min t)
  823.                       (pop path)))))
  824.   path)
  825.  
  826. (defun delete-right-node (path parent-node first-right)
  827.   "Delete the parent node where first-right = (btree-right parent-node)
  828. and (btree-left first-right) = nil.
  829. Path is a right turn from the path to the parent node.
  830. Copy the keys and val of first-right
  831. into the parent node and remove the first-right node, modifying the tree" 
  832.   (let ((right (btree-right first-right)))
  833.     (copy-info first-right parent-node :right t :max t)
  834.     (if right
  835.       (progn
  836.         (copy-info right first-right :right t :max t :left t :min t)
  837.         (setf (btrail-dir (first path)) *right*))
  838.       (pop path))
  839.     path))
  840.  
  841. (defun delete-first-greater (path)
  842.   "Delete the first node which is greater than the last node on the path"
  843.   (let (first-right
  844.         (node (btrail-node (first path)))
  845.         parent-node)
  846.     (setq parent-node node
  847.           path (turn-immediate path *right*)
  848.           first-right (btree-right parent-node)
  849.           node first-right)
  850.     (if (null (btree-left first-right))
  851.       (delete-right-node path parent-node first-right)
  852.       (delete-extreme-left path parent-node first-right))))
  853.  
  854. (defun find-path (key path &key (order-function #'compare) (descend nil))
  855.   "Find the key starting with the path path."
  856.   (let (temp dir node alt-path new-key)
  857.     (when (and path
  858.                (setf temp (first path))
  859.                (null (setf dir (btrail-dir temp))))
  860.       (setf dir (btrail-prev temp)) 
  861.       (pop path))
  862.     (loop
  863.       (unless path
  864.         (push (list nil key) path)
  865.         (return path))
  866.       (setf temp (first path)
  867.             node (btrail-node temp)
  868.             dir (btrail-dir temp)
  869.             new-key (btree-key node))
  870.       (select (funcall order-function key new-key)
  871.         (*equal*
  872.          (return path))
  873.         (*before*
  874.          (cond ((or (is-leaf node)
  875.                     (and (not descend)
  876.                          (equal dir *right*)
  877.                          (equal (funcall order-function key (min-val node))
  878.                                 *before*)))
  879.                 (return (push (list nil key *left*) path)))
  880.                ((setf node (btree-left node))
  881.                 (setf (btrail-dir temp) *left*)
  882.                 (push (list *equal* node) path))
  883.                (t (return (push (list nil key) path)))))
  884.         (*after*
  885.          (cond  ((or (equal dir *right*)
  886.                      (is-leaf node))
  887.                  (if (setf alt-path (retract-path key path order-function))
  888.                    (setf path alt-path
  889.                          temp (first path)
  890.                          node (btrail-node temp)
  891.                          dir (btrail-dir temp))
  892.                    (return (push (list nil key *right*) path))))
  893.                 ((setf node (btree-right node))
  894.                  (setf (btrail-dir temp) *right*)
  895.                  (push (list *equal* node) path))
  896.                 (t (return (push (list nil key *right*) path)))))))))
  897.  
  898. (defun quick-path (key root &key (order-function #'compare))
  899.   "Uses the min and max links to find a path (if it exists) to the node with key,
  900. starting with the path at the root"
  901.   (let (node new-key)
  902.     (setf node root)
  903.     (loop
  904.       (setf new-key (btree-key node))
  905.       (select (funcall order-function key new-key)
  906.         (*equal*
  907.          (return node))
  908.         (*before*
  909.          (cond ((is-leaf node)
  910.                 (return nil))
  911.                ((setf node (btree-left node)) t)
  912.                (t (return node))))
  913.         (*after*
  914.          (cond  ((is-leaf node)
  915.                  (return nil))
  916.                 ((setf node (btree-right node))
  917.                  t)
  918.                 (t (return nil))))))))
  919.  
  920. (defun find-root (path)
  921.   "Given a path, finds the root node of the path"
  922.   (when path
  923.     (btrail-node (first (last path)))))
  924.  
  925. (defun root-find (tree keys order-function)
  926.   "Determines whether all keys are in the rooted tree, using quick path"
  927.   (let* (node)
  928.     (loop for a-key in keys
  929.           do (setf node (quick-path a-key tree :order-function order-function))
  930.           when (null node) do (return  nil)
  931.           finally (return t))))
  932.  
  933. (defun slow-find (root keys the-pred)
  934.   (let* ((root-path (root-path root))
  935.          path (mine (first root-path)))
  936.     (loop for a-key in keys
  937.           do (setf (btrail-dir mine) *equal*
  938.                    path (find-path a-key root-path :order-function the-pred))
  939.           when (or (null path)
  940.                    (equal (btrail-node (first path))
  941.                           a-key))
  942.           do (return nil)
  943.           finally (return t))))
  944.  
  945. (defun get-next-node (start-path)
  946.   "Gets the next node not already visited along the start-path.
  947. The following prints every node of the tree in ascending order
  948. (loop with path = (root-path tree)
  949.       do (setq path (get-next-node path))
  950.       while path
  951.       do (print (btree-key (btrail-node (first path)))))"
  952.   (when start-path
  953.     (loop with path = start-path and node and new-path and dir and node-path = nil 
  954.           while path
  955.           do (setq node (first path)
  956.                    dir (btrail-dir node)
  957.                    node (btrail-node node))
  958.           do (if (is-leaf node)
  959.                (if (equal dir *right*)
  960.                  (pop path)
  961.                  (progn
  962.                    (setf (btrail-dir (first path)) *right*)
  963.                    (setq node-path path
  964.                          path nil)))
  965.                (select dir
  966.                  (*done* (setq new-path (turn-immediate path *right*))
  967.                          (if new-path
  968.                            (setq path new-path)
  969.                            (pop path)))
  970.                  (*right* (pop path))
  971.                  (*left* (setf (btrail-dir (first path)) *done*)
  972.                          (setq node-path path
  973.                                path nil))
  974.                  (t (setq new-path (turn-immediate path *left*))
  975.                     (if new-path
  976.                       (setq path new-path)
  977.                       (setf (btrail-dir (first path)) *left*)))))
  978.           finally (return node-path))))
  979.  
  980. (defun from-btree-to-list (tree &key (get-val #'(lambda (key val) (list key val))))
  981.   "Traverses the balanced binary tree in key order, 
  982. collecting (funcall get-val  key value)"
  983.   (loop with path = (root-path tree) and node
  984.         do (setq path (get-next-node path))
  985.         while path
  986.         do (setq node (btrail-node (first path)))
  987.         collect (funcall get-val (btree-key node) (btree-val node))))
  988.  
  989. ;; -> path adjustment
  990. (defun adjust-path (path w-node y-node)
  991.   "adjusts the path, so that if w-node is the first node along the path,
  992. w-node is the appropriate turn from its parent y-node"
  993.   (when (eq (btrail-node (first path)) w-node)
  994.     (setf (btrail-dir (first path))
  995.           (cond((eq (btree-left w-node) y-node) *left*)
  996.                ((eq (btree-right w-node) y-node) *right*)
  997.                (t (break)))))
  998.   path)
  999.  
  1000. (defun fix-path (path)
  1001.   "Fixes the path, adjusting the min and max values for left/right turns"
  1002.   (fix-left-path path)
  1003.   (fix-right-path path))
  1004.  
  1005. (defun fix-left-path (path)
  1006.   (when path
  1007.     (loop
  1008.       while (rest path)
  1009.       with min = (btrail-node (first path)) and x-trail = (first path) and node
  1010.       do (pop path)
  1011.       do (setq x-trail (first path))
  1012.       while (equal (btrail-dir x-trail) *left*)
  1013.       do (setf (btree-min (btrail-node x-trail)) (get-min min))
  1014.       finally (setf (btree-min (setq node (btrail-node (first path))))
  1015.                     (get-min (btree-left node))))))
  1016.  
  1017. (defun fix-right-path (path)
  1018.   (when path
  1019.     (loop
  1020.       with max = (btrail-node (first path)) and x-trail and node
  1021.       while (rest path)
  1022.       do (pop path)
  1023.       do (setq x-trail (first path))
  1024.       while (equal (btrail-dir x-trail) *right*)
  1025.       do (setf (btree-max (btrail-node x-trail)) (get-max max))
  1026.       finally (setf (btree-max (setq node (btrail-node (first path))))
  1027.                     (get-max (btree-right node))))))
  1028.  
  1029.  
  1030. ;;  --> balance/direction routines
  1031.  
  1032. (defun rev-dir (dir)
  1033.   "reverses the direction left <-> right"
  1034.   (if (= dir *right*)
  1035.     *left*
  1036.     *right*))
  1037.  
  1038. (defun all-height-balanced (tree)
  1039.   "Return t iff the tree is height balanced 
  1040. That is, the heights of the left/right branches differ by at most 1."
  1041.   (or (null tree)
  1042.       (and (height-balanced tree)
  1043.            (all-height-balanced (btree-left tree))
  1044.            (all-height-balanced (btree-right tree)))))
  1045.  
  1046. (defun height-balanced (tree)
  1047.   (or (null tree)
  1048.       (let ((left (height-btree (btree-left tree)))
  1049.             (right (height-btree (btree-right tree))))
  1050.         (if (<= (abs (- left right)) 1) 
  1051.           t
  1052.           (progn (print-tree tree)
  1053.                  (print-db left right)
  1054.                  nil)))))
  1055.  
  1056. (defun rev-balance (prev-pivot pivot)
  1057.   "reverses the direction left-taller <-> right-taller"
  1058.   (if (eq prev-pivot (btree-right pivot))
  1059.     *left-taller*
  1060.     *right-taller*))
  1061.  
  1062. (defun to-balance (prev-pivot pivot)
  1063.   (if (eq prev-pivot (btree-right pivot))
  1064.     *right-taller*
  1065.     *left-taller*))
  1066.  
  1067. (defun add-balance (path)
  1068.   "Called after adding a node when rebalancing may be required.
  1069. Adjusts the balance factors and rotates the tree if necessary. 
  1070. Stops when the tree is balanced or after a rotation."
  1071.   (let* ((balance-point path)
  1072.          (old-path path)
  1073.          (temp (pop path))
  1074.          (pivot (btrail-node temp))
  1075.          prev-pivot
  1076.          new-balance
  1077.          (balance (btree-balance pivot)))
  1078.     (loop
  1079.       (unless path
  1080.         (return t))
  1081.       (setf prev-pivot pivot
  1082.             old-path path
  1083.             temp (pop path)
  1084.             pivot (btrail-node temp)
  1085.             balance (btree-balance pivot))
  1086.       (unless (and path (= balance *balanced*))
  1087.         (return t))
  1088.       (setf (btree-balance pivot)
  1089.             (to-balance prev-pivot pivot)))
  1090.     (setf new-balance (if (eq (btree-left pivot) prev-pivot)
  1091.                         *left-taller*
  1092.                         *right-taller*)
  1093.           balance (btree-balance pivot))
  1094.     (if (not (= balance new-balance))
  1095.       (incf (btree-balance pivot) new-balance)
  1096.       (progn (rotate-tree prev-pivot pivot new-balance)
  1097.              (setf balance-point
  1098.                    old-path)))
  1099.     (check-leaf pivot)
  1100.     balance-point))
  1101.  
  1102. (defun del-balance (path)
  1103.   "Called after deleting a node when rebalancing may be required.
  1104. Adjusts the balance factors and rotates the tree
  1105. if necessary. Continues rebalancing until 
  1106. 1. the tree becomes height balanced
  1107. 2. rebalancing has reached the root.
  1108. 3. the b-node has height h+1 and we have rotated the tree."
  1109.   (when path
  1110.     (let ((balance-point path))
  1111.       (loop
  1112.         with terminate and temp and z-node and dir
  1113.         until (null path)
  1114.         do (setq temp (first path)
  1115.                  dir (btrail-dir temp)
  1116.                  z-node (btrail-node (first path)))
  1117.         do (select (btree-balance z-node)
  1118.              (dir (setf (btree-balance z-node) *balanced*)
  1119.                   (if (rest path) 
  1120.                     (pop path)
  1121.                     (setq terminate t)))
  1122.              (*balanced*
  1123.               (setf (btree-balance z-node) (rev-dir dir)) ; from (- 
  1124.               (setq terminate t))
  1125.              (t (multiple-value-setq (path z-node terminate)
  1126.                   (del-rotate path))
  1127.                 (check-leaf z-node)))
  1128.         until terminate)
  1129.       (let ((tree (find-root path)))
  1130.         (unless (check-tree tree 
  1131.                             (min-val tree) 
  1132.                             (max-val tree))
  1133.           (break "not-balanced")))
  1134.       balance-point)))
  1135.  
  1136. ;;--> rotating trees to correct the balance
  1137. (defun rotate-tree (prev-pivot pivot new-balance)
  1138.   (if (is-leaf pivot)
  1139.     pivot
  1140.     (let (child)
  1141.       (setq child
  1142.             (if (= new-balance *right-taller*)
  1143.               (btree-right pivot)
  1144.               (btree-left pivot)))
  1145.       (multiple-value-bind (w-node y-node z-node) 
  1146.                            (if (= (btree-balance prev-pivot) (- new-balance))
  1147.                              (rotate-double pivot child (if (equal (btree-balance child) *left-taller*)
  1148.                                                           (btree-left child)
  1149.                                                           (btree-right child)))
  1150.                              (rotate-single pivot child))
  1151.         (when y-node
  1152.           (setf (btree-min y-node) (get-min (btree-left y-node))
  1153.                 (btree-max y-node) (get-max (btree-right y-node))))
  1154.         (when z-node
  1155.           (setf (btree-min z-node) (get-min (btree-left z-node))
  1156.                 (btree-max z-node) (get-max (btree-right z-node))))
  1157.         
  1158.         (when w-node
  1159.           (setf (btree-min w-node) (get-min (btree-left w-node))
  1160.                 (btree-max w-node) (get-max (btree-right w-node))))
  1161.         (values w-node y-node z-node)))))
  1162.  
  1163. (defun rotate-single (a-node b-node)
  1164.   (let* ((dir (if (eq b-node (btree-left a-node)) *left* *right*))
  1165.          (alpha (link (rev-dir dir) a-node))
  1166.          (beta (link (rev-dir dir) b-node))
  1167.          (gamma (link dir b-node)))
  1168.     (swap-key a-node b-node)
  1169.     (rotatef a-node b-node)
  1170.     (set-link dir b-node gamma)
  1171.     (set-link  (rev-dir dir) b-node a-node)
  1172.     (set-link dir a-node beta)
  1173.     (set-link  (rev-dir dir) a-node alpha)
  1174.     (setf (btree-balance a-node) *balanced*)
  1175.     (setf (btree-balance b-node) *balanced*)
  1176.     (values b-node a-node)))
  1177.  
  1178. (defun rotate-double (a-node b-node x-node)
  1179.   (let* ((dir (if (eq b-node (btree-left a-node)) *left* *right*))
  1180.          (alpha (link  (rev-dir dir) a-node))
  1181.          (beta (link  (rev-dir dir) x-node))
  1182.          (gamma (link dir x-node))
  1183.          (delta (link dir b-node))
  1184.          (balance (btree-balance (link  (rev-dir dir) b-node))))
  1185.     (swap-key a-node x-node)
  1186.     (rotatef a-node x-node)
  1187.     (set-link dir b-node delta)
  1188.     (set-link  (rev-dir dir) b-node gamma)
  1189.     (set-link dir a-node beta)
  1190.     (set-link  (rev-dir dir) a-node alpha)
  1191.     (set-link  (rev-dir dir) x-node a-node)
  1192.     (fix-max-min b-node)
  1193.     (fix-max-min a-node)
  1194.     (fix-max-min x-node)
  1195.     (multiple-value-bind (a-balance b-balance)
  1196.                          (select balance
  1197.                            (dir (values  (rev-dir dir) *balanced*))
  1198.                            (*balanced* (values *balanced* *balanced*))
  1199.                            ( (rev-dir dir) (values *balanced* dir)))
  1200.       (setf (btree-balance a-node) a-balance
  1201.             (btree-balance b-node) b-balance
  1202.             (btree-balance x-node) *balanced*)
  1203.       (check-leaf a-node)
  1204.       (check-leaf b-node)
  1205.       (check-leaf x-node)
  1206.       (values x-node b-node a-node))))
  1207.  
  1208. ; addition routines
  1209.  
  1210. (defun add-node (key val path order-function)
  1211.   "Adds the node with key and val to the tree, starting with the path,
  1212. using the order-function.
  1213. Adds the node only if the key is not in the tree."
  1214.   (if path
  1215.     (let (temp dir)
  1216.       (setf path
  1217.             (find-path key path :order-function order-function :descend t)
  1218.             temp (first path)
  1219.             dir (btrail-dir temp))
  1220.       (unless dir
  1221.         (setf path
  1222.               (insert-node (make-btree :key key :val val)
  1223.                            path order-function)))
  1224.       path)
  1225.     (root-path (make-btree :key key :val val))))
  1226.  
  1227. (defun add-node-right (new-node path order-function)
  1228.   "Adds the node with key and val to the tree, starting with the path,
  1229. to the right of the first node on the path using the order-function."
  1230.   (if path
  1231.     (let* ((temp (first path))
  1232.            (root (find-root path))
  1233.            (old-path (root-path root))
  1234.            (key (copy-tree (btree-key new-node)))
  1235.            (node (btrail-node temp)))
  1236.       (setf (btree-right node) new-node)
  1237.       (setf (btrail-dir temp) *right*)
  1238.       (push (make-btrail :dir *equal* :node new-node) path)
  1239.       (q-adjust-max path)
  1240.       (q-adjust-min path)
  1241.       (setf path (add-balance path))
  1242.       
  1243.       (unless path
  1244.         (print 'empty-path)
  1245.         (setf path old-path))
  1246.       (setq root (find-root path))
  1247.       (setq path (find-path key (root-path root) :order-function order-function))
  1248.       path)
  1249.     (root-path new-node)))
  1250.  
  1251. (defun insert-node (new-node path order-function)
  1252.   "Inserts the new-node with path pointing to the new-node,
  1253. using the order-function."
  1254.   (let* ((temp (pop path))
  1255.          (dir (btrail-prev temp))
  1256.          (key (btree-key new-node))
  1257.          node)
  1258.     (setf temp (first path)
  1259.           node (btrail-node temp)
  1260.           dir (funcall order-function key (btree-key node)))
  1261.     (cond ((= dir *before*)
  1262.            (add-turn new-node node temp path *left*))
  1263.           ((and nil (is-leaf node)) ;;; changed
  1264.            (swap-key node new-node)
  1265.            (add-turn new-node node temp path *left*))
  1266.           (t (add-turn new-node node temp path *right*)))
  1267.     (q-adjust-max-min path)
  1268.     (setf path (add-balance path))
  1269.     path))
  1270.  
  1271. ;; --> deletion routines
  1272.  
  1273. (defun del-current-node (path)
  1274.   "delete the first node on the path since the left/right link is null."
  1275.   (let* (child
  1276.          (node (btrail-node (first path)))
  1277.          (parent (when  (rest path)
  1278.                    (second path)))
  1279.          (parent-node (when parent
  1280.                         (btrail-node parent))))
  1281.     (unless parent-node 
  1282.       (setq parent (first path))
  1283.       (setq parent-node node))
  1284.     (if (setq child (or (btree-left node) (btree-right node)))
  1285.       (progn
  1286.         (if (eq parent-node node)
  1287.           (progn
  1288.             (copy-info child node :left t :min t
  1289.                        :right t :max t :balance t))
  1290.           (copy-info child node :left t :min t
  1291.                      :right t :max t)))
  1292.       (progn
  1293.         (if parent-node
  1294.           (if (eq node (btree-left parent-node))
  1295.             (setf (btree-left parent-node) nil)
  1296.             (setf (btree-right parent-node) nil)))
  1297.         (pop path)))
  1298.     (fix-max-min parent-node)
  1299.     path))
  1300.  
  1301. (defun del-rotate (path)
  1302.   "Tree rotation of the tree rooted at the first node of path"
  1303.   (let ((z-node (btrail-node (first path)))
  1304.         (dir (btrail-dir (first path)))
  1305.         y-node
  1306.         terminate
  1307.         z-bal)
  1308.     (setq y-node (if (= dir *left*)
  1309.                    (btree-right z-node)
  1310.                    (btree-left z-node)))
  1311.     (when (equal (btree-balance y-node) *balanced*)
  1312.       (setq terminate t))
  1313.     (setq z-bal (btree-balance z-node))
  1314.     (multiple-value-bind (new-w new-y new-z)
  1315.                          (rotate-tree y-node z-node  (rev-dir dir))
  1316.       (fix-path path)
  1317.       (if terminate
  1318.         (progn
  1319.           (setf (btree-balance new-w) (btrail-dir (first path))
  1320.                 (btree-balance new-y) z-bal)
  1321.           (values path new-z terminate))
  1322.         (next-del-rotate path new-z new-w terminate)))))
  1323.  
  1324. (defun delete-node (path order-function)
  1325.   "delete the first node in the path"
  1326.   (declare (ignore order-function))
  1327.   (let* ((temp (when path (first path)))
  1328.          (dir (when temp (btrail-dir temp)))
  1329.          (node (when temp (btrail-node temp)))
  1330.          (del-balance t))
  1331.     (if (null dir)
  1332.       (progn
  1333.         (pop path)
  1334.         path)
  1335.       (progn
  1336.         (if (or (null (btree-right node)) (null (btree-left node)))
  1337.           (setq del-balance (rest path)
  1338.                 path (del-current-node path))
  1339.           (setq path (delete-first-greater path)))
  1340.         (when path
  1341.           (fix-path path)
  1342.           (if (and path del-balance)
  1343.             (setq path (del-balance path))
  1344.             (when del-balance (pop path))))
  1345.         path))))
  1346.  
  1347. (defun next-del (path z-node)
  1348.   (let ((t-node z-node)
  1349.         temp
  1350.         (new-path path)
  1351.         dir)
  1352.     (pop path)
  1353.     (when path
  1354.       (setq new-path path
  1355.             temp (first new-path)
  1356.             z-node (btrail-node temp)
  1357.             dir (btrail-dir temp))
  1358.       (setf (btrail-dir temp)
  1359.             (if (eq t-node (btree-right z-node))
  1360.               *right*
  1361.               *left*)))
  1362.     (values path z-node dir)))
  1363.  
  1364. (defun next-del-rotate (path z-node w-node terminate)
  1365.   (let (temp
  1366.         (new-path path))
  1367.     (pop path)
  1368.     (when path
  1369.       (setq temp (first path))
  1370.       (setq z-node w-node)
  1371.       (setq new-path path)
  1372.       (setq temp (first new-path)
  1373.             z-node (btrail-node temp)))
  1374.     (q-adjust-max-min path)
  1375.     (values path z-node (or terminate (null path)))))
  1376.  
  1377. ;; --> testing routines
  1378. (defun gen-trees (n elements &key (max-val 1000))
  1379.   "Generate n random trees containing elements nodes
  1380. with keys chosen from 0 ... max-val"
  1381.   (let (test new-tree)
  1382.   (dotimes (i n)
  1383.     (setq test nil)
  1384.     (dotimes (j elements)
  1385.       (pushnew (random max-val) test))
  1386.     (setq new-tree (to-btreek test #'compare))
  1387.     (unless
  1388.       (check-tree new-tree (min-val new-tree) (max-val new-tree))
  1389.       (print-db test i)
  1390.       (print-tree new-tree :title 'bad-tree)
  1391.       (break)))))
  1392.  
  1393. (defun tree-test (n m &key (max-val 1000))
  1394.   "Create n random trees with m keys."
  1395.   (dotimes (len m)
  1396.     (print-db (1+ len))
  1397.     (gen-trees n (1+ len) :max-val max-val)))
  1398.  
  1399. (defun test-del (root key-list)
  1400.   "deletes the specified keys from the root and prints
  1401. the resulting trees"
  1402.   (let (path temp dir)
  1403.     (print-tree root :title "original")
  1404.     (dolist (key key-list)
  1405.       (setf path (find-path key (root-path root))
  1406.             temp (first path)
  1407.             dir (btrail-dir temp))
  1408.       (format t "~&deleting key:  ~s~%" key)
  1409.       (when dir
  1410.         (setf path (delete-node path #'compare)))
  1411.       (print-tree root :title (format nil "deleted key: ~s~%" key))
  1412.       (print-path path :title (format nil "path after:~%")))))
  1413.  
  1414. (defun del-all-nodes (nodes  &key debug)
  1415.   "Delete all the nodes in the tree"
  1416.   (del-nodes nodes (algebra::permute nodes) :debug debug))
  1417.  
  1418. (defun del-nodes (seq dels &key debug)
  1419.   "Delete the nodes in dels from the tree with nodes seq"
  1420.   (let ((tree (to-btreek seq  #'compare))
  1421.         path)
  1422.     (when debug (print tree) (print-tree tree :title "start") (print-db seq))
  1423.     (loop for key in dels
  1424.           when debug do (print-db key)
  1425.           do (setq path (find-path key (root-path tree)
  1426.                                    :order-function #'compare)
  1427.                    tree (find-root (delete-node path #'compare)))
  1428.           when debug do (print tree) (print-tree tree :title (format nil "deleted: ~d" key))
  1429.           unless (check-tree tree 
  1430.                                        (min-val tree) 
  1431.                                        (max-val tree))
  1432.           do (print-tree tree) (print-db seq dels)
  1433.           (break))))
  1434.  
  1435. (defun del-trees (n elements  &key (max-val 1000) debug)
  1436.   "Generate a n random trees with elements integer keys (0 .. (1- max-val))
  1437. and delete all the nodes from each tree."
  1438.   (let (vals)
  1439.   (dotimes (i n)
  1440.     (setq vals nil)
  1441.     (dotimes (j elements)
  1442.       (pushnew (random max-val) vals))
  1443.     (del-all-nodes vals :debug debug))))
  1444.  
  1445. #|
  1446. ;; create a btree with nodes in the key list and with value fields = key*key
  1447. (defparameter my-tree nil)
  1448. (defun square-tree (key-list)
  1449.   (let (tree)
  1450.     (loop for key in key-list
  1451.           do (setq tree 
  1452.                    (find-root (add-node key (* key key) (root-path tree) #'compare))))
  1453.     tree))
  1454.  
  1455. (setq my-tree (square-tree '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21)))
  1456.  
  1457. (metric-btree my-tree)                     ; nodes=21 height=5 ideal/actual = 88%
  1458.                                         ; for remainder see below
  1459. (print-tree my-tree)
  1460.  
  1461. ;; find the path to the node with key 11 and print it
  1462. (setq path (find-path 11 (root-path my-tree) :order-function #'compare))
  1463. (print-path path)
  1464.  
  1465. ;; find the node with key 11
  1466. (setq node (quick-path 11 my-tree :order-function  #'compare))
  1467.  
  1468. ;; find the node with key 100 (doesn't exist)
  1469. (setq node (quick-path 100 my-tree :order-function  #'compare))
  1470.  
  1471. ;; Print the keys in order using get-next-node
  1472. (loop with path = (root-path my-tree)
  1473.       do (setq path (get-next-node path))
  1474.       until (null path)
  1475.       do (print (btree-key (btrail-node (first path)))))
  1476. |#
  1477. #|
  1478.  R 8   [1 21]  
  1479.     4 L [1 7]  
  1480.      2 L [1 3]  
  1481.       1 L [NIL NIL]  
  1482.       3 R [NIL NIL]  
  1483.      6 R [5 7]  
  1484.       5 L [NIL NIL]  
  1485.       7 R [NIL NIL]  
  1486.     16 R [9 21]  
  1487.      12 L [9 15]  
  1488.       10 L [9 11]  
  1489.        9 L [NIL NIL]  
  1490.        11 R [NIL NIL]  
  1491.       14 R [13 15]  
  1492.        13 L [NIL NIL]  
  1493.        15 R [NIL NIL]  
  1494.    R 18 R [17 21]  
  1495.       17 L [NIL NIL]  
  1496.       20 R [19 21]  
  1497.        19 L [NIL NIL]  
  1498.        21 R [NIL NIL] 
  1499.  
  1500.   Path length 5 
  1501. 11   [NIL NIL]  
  1502. 10 R [9 11]  
  1503. 12 L [9 15]  
  1504. 16 L [9 21]  
  1505. 8 R [1 21] R
  1506.  
  1507. (NIL NIL 11 121 NIL NIL 0)
  1508.  
  1509. nil
  1510. |#